package com.muki.jms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.log4j.Logger;

public class JmsConsumer {

	private Logger log = Logger.getLogger(JmsConsumer.class);
	private JmsPreparedConnection prepared = null;
	private Session session = null;
	private MessageConsumer consumer = null;

	public JmsConsumer() {
		prepared = new JmsPreparedConnection();
	}

	public void bindQueue(String queue) throws JMSException {
		//如果producer为空，则绑定queue
		if(session==null)
			session = prepared.init();
		Queue que = session.createQueue(queue);
		if(que!=null) {
			consumer = session.createConsumer(que);
			log.info("绑定 queue:"+queue);
		} else
			log.info("the que "+queue+" creating failed");
	}	

	public void bindTopic(String topic) throws JMSException {
		if(session==null)
			session = prepared.init();
		Topic top = session.createTopic(topic);
		if(top!=null)
			consumer = session.createConsumer(top);
		else
			log.info("the topic "+topic+" creating error!");
	}
	
	public void receive(Message message) throws JMSException {
		consumer.receive(10000);
	}

	public MessageConsumer getConsssumer() {
		return consumer;
	}
}
